package com.atguigu.base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncVSLockDemo {
    public synchronized void a() {
        System.out.println(Thread.currentThread().getName() + "线程进来了");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private final Lock lock = new ReentrantLock();

    public void b() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "线程进来了");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "没抢到锁重试");
        }
    }

    public void c() {
        try
        {
            if (lock.tryLock(2L,TimeUnit.SECONDS))
            {
                try
                {
                    System.out.println(Thread.currentThread().getName() + "线程进来了");
                    try { TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) { e.printStackTrace(); }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "超过两秒没抢到锁重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();
        new Thread(() -> {
            syncVSLockDemo.c();
        }, "t1").start();
        new Thread(() -> {
            syncVSLockDemo.c();
        }, "t2").start();
    }
}
